<template>
  <el-dialog
    class="met-dialog type2"
    :title="dialog.title"
    width="1000px"
    :visible.sync="dialog.visible"
    :append-to-body="true"
  >
    <template v-if="dialog.visible">
      <!-- 会议室预定 -->
      <div class="row">
        <devformVue label="会议室名称 ">
          {{ ruleForm.name || ruleForm.roomName }}
        </devformVue>
      </div>
      <div class="row">
        <devformVue label="容纳人数 " classname="w2">
          {{ ruleForm.capacity }}
        </devformVue>
        <devformVue label="管理员 " classname="w2">
          {{ ruleForm.capacity }}
        </devformVue>
      </div>
      <div class="row">
        <devformVue label="会议室地点 " classname="w2">
          {{ ruleForm.address }}
        </devformVue>
        <devformVue label="设备状态 " classname="w2">
          <dict-tag
            style="display: inline-block"
            :options="dict.type.equipment_status"
            :value="ruleForm.deviceStatus"
          />
        </devformVue>
      </div>

      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="160px"
        class="demo-ruleForm dev-form smallinput"
        :inline="true"
        :disabled="editType == 3"
      >
        <el-form-item label="会议标题" prop="title">
          <el-input
            type="input"
            placeholder="请输入内容"
            v-model="ruleForm.title"
            @blur="onChooseRange"
            maxlength="30"
          ></el-input>
        </el-form-item>
        <el-form-item label="出席人员" >
          <el-select
            v-model="ruleForm.userList"
            placeholder="请选择出席人员"
            multiple 
            filterable 
            style="width: 100%"
          >
          <el-option
            :label="item.userName"
            :key="item.userId"
            v-for="item in userList"
            :value="item.userId"
          ></el-option>
        </el-select>
        </el-form-item>
        <el-form-item label="会议日期" prop="usageDate">
          <el-date-picker
            v-model="ruleForm.usageDate"
            type="date"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
            :pickerOptions="pickerOptions"
            @change="onChooseRange"
          >
          </el-date-picker>
          <el-time-picker
            is-range
            v-model="ruleForm.timeRange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            placeholder="选择时间范围"
            value-format="HH:mm:ss"
            @change="onChooseRange"
          >
          </el-time-picker>
        </el-form-item>
        <el-form-item label="会议内容" prop="text">
          <el-input
            type="textarea"
            placeholder="请输入内容"
            v-model="ruleForm.description"
            maxlength="120"
            show-word-limit
            style="width: 700px"
          ></el-input>
        </el-form-item>
        <el-form-item label="审批说明" prop="remark" v-if="editType == 3">
          {{ ruleForm.remark }}
        </el-form-item>

        <el-form-item label=" " prop="area" v-if="editType != 3">
          <el-button type="primary" @click="submitForm('ruleForm')"
            >确定</el-button
          >
          <el-button @click="dialog.visible = false">取消</el-button>
        </el-form-item>
      </el-form>

      <!-- 日程部分-->
      <div style="box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); padding: 10px">
        <el-date-picker
          v-model="queryStartDate"
          type="date"
          placeholder="选择日期"
          class="datechose"
          @change="quertStart(queryStartDate)"
          max-time="23:59:59"
        >
        </el-date-picker>
        <FullCalendar
          id="calendar"
          :options="calendarOptions"
          ref="FullCalendar"
          :event-overlap="false"
        />
        <!-- 点击会议弹窗内容 -->
        <div v-if="selectedEvent">
          <el-dialog
            :close-on-click-modal="true"
            :visible="this.showDialog"
            @close="closeDialog()"
            title="日程详情"
            append-to-body
          >
            <div class="modal-title">{{ this.selectedEvent.title }}</div>
            <p>开始时间：{{ this.selectedEvent.start }}</p>
            <p>结束时间：{{ this.selectedEvent.end }}</p>
            <p>会议内容：{{ this.selectedEvent.context }}</p>
          </el-dialog>
        </div>
      </div>
      <!-- <div class="foot">
      <el-button type="primary" @click="submodal('ruleForm')" class="modal-btn"
        >确定</el-button
      >
    </div> -->
    </template>
  </el-dialog>
</template>

<script>
import FullCalendar from "@fullcalendar/vue";
import dayGridPlugin from "@fullcalendar/daygrid";
import timeGridPlugin from "@fullcalendar/timegrid";
import interactionPlugin from "@fullcalendar/interaction";
import devformVue from "../caseManage/devform";
const colorList = [
  "#ff9a9e",
  "#84fab0",
  "#EB7347",
  "#c2e9fb",
  "#a18cd1",
  "#00f2fe",
];
import { meetingmine, rommdetail, meeting, select, getAllUser } from "@/api/met";
import moment from "moment";
// https://blog.csdn.net/SYQ15544423296/article/details/134466036 https://blog.csdn.net/m0_63300795/article/details/132101178 FullCalendar文档参考
export default {
  components: {
    FullCalendar,
    devformVue,
  },
  dicts: ["equipment_status"],
  data() {
    var validateusageDate = (rule, value, callback) => {
      if (!value) {
        callback(new Error("会议日期不可为空！"));
      } else if (
        !this.ruleForm.timeRange ||
        this.ruleForm.timeRange.length == 0
      ) {
        callback(new Error("会议时间不可为空！"));
      } else {
        callback();
      }
    };
    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 1000 * 24 * 3600;
        },
      },
      editType: "",
      dialog: {
        visible: false,
        title: "会议室预定",
      },
      ruleForm: {
        text: "",
        usageDate: "",
        description: "",
        timeRange: [],
        userList: []
      },
      //普通查询时间
      queryStartDate: null,
      //日程弹窗开关
      showDialog: false,

      //日程弹窗内容
      selectedEvent: null,
      // 点击事件触发函数
      //日程内容集合
      meetingArr: [],
      calendarOptions: {
        eventOverlap: false,
        slotEventOverlap: false,
        // 加载的视图
        plugins: [dayGridPlugin, timeGridPlugin, interactionPlugin],
        // 视图类型 初始显示的视图 视图名称规则 比如dayGridPlugin去掉Plugin 加上Month或者Week或者Day
        initialView: "timeGridWeek",

        // 语言选项  设置为中文后 部分文本会替换为中文 但是不全面
        contentHeight: 350,
        locale: "zh-cn",
        // 配置日历头部
        // 按钮: prev为切换(上)下一月(/周/日)   next today 跳转到今天
        // 文本: title 年月(YYYY-MM)
        // 按钮: dayGridMonth月 timeGridWeek周 timeGridDay日
        headerToolbar: {
          right: "today prev,next",
          center: "title",
          left: "timeGridWeek", //dayGridMonth,,timeGridDay
        },
        // 设置各种按钮的文字  默认是英文的
        buttonText: {
          today: "今天",
          month: "月视图",
          week: "周视图",
          day: "日视图",
          list: "表",
        },
        // 初始就存在的事件【日程内容】
        initialEvents: [],
        // 是否可拖拽
        editable: false,
        // 是否可选择添加
        selectable: true,
        // 选择时触发函数
        select: this.handleDateSelect,
        // 点击事项触发函数
        dateClick: this.handleEventClick, //点击时间触发
        eventClick: this.handleEventClick, //点击已有事件触发
        // 移动事项或者拓展事项时间触发函数
        eventsSet: this.handleEvents,
        customButtons: {
          next: {
            click: this.handleViewRenderNext,
          },
          prev: {
            click: this.handleViewRenderPrev,
          },
        },
        allDayText: "全天",
        // 最小时间
        slotMinTime: "00:00:00",
        // 最大时间
        slotMaxTime: "23:59:59",
        // 是否可以进行（拖动、缩放）修改
      },
      rules: {
        description: [
          { required: true, message: "请填写会议内容", trigger: "blur" },
        ],
        title: [
          { required: true, message: "请填写会议标题", trigger: "change" },
          {
            trigger: "change",
          },
        ],
        usageDate: [
          { required: true, validator: validateusageDate, trigger: "blur" },
        ],
      },
      isChooseList: [],
      roomId: "",
    };
  },
  methods: {
    getAllUser() {
      getAllUser().then((res) => {
        this.userList = res.data;
      });
    },
    handleViewRenderNext(event) {
      let api = this.$refs.FullCalendar.getApi();
      api.next();
      this.select(api.view.currentStart);
    },
    handleViewRenderPrev() {
      let api = this.$refs.FullCalendar.getApi();
      api.prev();
      this.select(api.view.currentStart);
    },
    select(date) {
      let timer = new Date(date).getTime();
      let start = moment(timer - 7 * 24 * 3600 * 1000).format(
        "YYYY-MM-DD HH:mm:ss"
      );
      let end =
        moment(timer + 7 * 24 * 3600 * 1000).format("YYYY-MM-DD") + " 23:59:59";
      select({ start, end, roomId: this.roomId }).then((res) => {
        let calendarApi = this.$refs.FullCalendar.getApi();

        let calendarFunc = calendarApi.view.calendar;
        let getEvents = calendarFunc.getEvents(); //获取数据

        if (getEvents && getEvents.length > 0) {
          //循环删除数据（通过ID）
          getEvents.map((item) => {
            calendarFunc.getEventById(item.id).remove();
          });
        }

        res.data.map((item, i) => {
          this.isChooseList.push({
            ...item,
            startTime: new Date(
              item.usageDate + " " + item.usageStartTime
            ).getTime(),
            endTime: new Date(
              item.usageDate + " " + item.usageEndTime
            ).getTime(),
          });
          calendarApi.addEvent({
            start: item.usageDate + " " + item.usageStartTime,
            end: item.usageDate + " " + item.usageEndTime,
            backgroundColor:
              this.ruleForm.id == item.id ? "#409EFF" : colorList[i % 6],
            textColor: "black",
            editable: false, //this.ruleForm.id == item.id,
            ...item,
            block: true,
          });
        });
      });
    },
    handlerSeelctAllow(event) {
      console.log("heihei", event);
    },
    onSave() {},
    handleDateSelect(event) {
      console.log(event);
      let date = moment(event.start).format("YYYY-MM-DD");
      let starTimer = moment(event.start).format("HH:mm:ss");
      let endTimer = moment(event.end).format("HH:mm:ss");

      this.ruleForm.usageDate = date;
      this.ruleForm.timeRange = [starTimer, endTimer];
      this.onChooseRange();
    },
    onChooseRange() {
      if (!this.ruleForm.usageDate || this.ruleForm.timeRange?.length != 2)
        return;
      let calendarApi = this.$refs.FullCalendar.getApi();
      let arr = this.isChooseList.filter(
        (v) => v.usageDate == this.ruleForm.usageDate
      );
      let timeRange = this.ruleForm.timeRange;
      for (let i = 0; i < arr.length; i++) {
        let v = arr[i];
        if (timeRange[1] === "00:00:00") {
          timeRange[1] = "23:59:59";
        }
        let RangeEndTime = new Date(v.usageDate + " " + timeRange[1]).getTime();
        let RangeStartTime = new Date(
          v.usageDate + " " + timeRange[0]
        ).getTime();
        let startRange =
          RangeStartTime <= v.startTime || RangeStartTime <= v.endTime;
        let endRange = RangeEndTime >= v.endTime || RangeEndTime >= v.startTime;
        console.log(
          "RangeEndTime <= v.endTime && RangeStartTime >= v.starTimer"
        );
        console.log(
          RangeEndTime <= v.endTime,
          RangeStartTime >= v.startTime,
          v.usageStartTime,
          timeRange[0],
          RangeStartTime,
          v.startTime
        );
        if (RangeEndTime <= v.endTime && RangeStartTime >= v.startTime) {
          this.$message("时间点选着冲突");
          return (this.ruleForm.timeRange = null);
        }
        if (startRange && endRange) {
          if (RangeStartTime > v.startTime) {
            timeRange[0] = moment(v.endTime).format("HH:mm:ss");
          } else if (RangeEndTime > v.startTime) {
            timeRange[1] = moment(v.startTime).format("HH:mm:ss");
          }
        }
      }

      console.log("结束");
      this.ruleForm.timeRange = timeRange;
      let calendarFunc = calendarApi.view.calendar;
      let id = this.ruleForm.id ? this.ruleForm.id : "add";
      calendarFunc.getEventById(id)?.remove();
      this.$nextTick(() => {
        calendarApi.addEvent({
          start: this.ruleForm.usageDate + " " + this.ruleForm.timeRange[0],
          end: this.ruleForm.usageDate + " " + this.ruleForm.timeRange[1],
          id: id,
          title: this.ruleForm.title || "",
          backgroundColor: "#409EFF",
          textColor: "black",
          editable: false,
        });
      });
    },
    //打开弹窗
    async open(e, type) {
      // 1为新增，2空为编辑 3为查看
      this.editType = type;
      let timeRange = e.usageStartTime
        ? [e.usageStartTime, e.usageEndTime]
        : null;
      let usageDate = e.usageDate
        ? e.usageDate + " 00:00:00"
        : moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
      this.ruleForm = {
        ...e,
        id: type != 1 ? e.id : "",
        roomId: type != 1 ? e.roomId : e.id,
        timeRange: timeRange,
      };
      this.roomId = type != 1 ? e.roomId : e.id;
      rommdetail(this.roomId).then((res) => {
        // 获取房间详情
        this.$delete(res.data, "id");
        this.$delete(res.data, "remark");
        this.ruleForm = { ...this.ruleForm, ...res.data };
      });
      this.dialog.visible = true;
      this.$nextTick(() => {
        this.quertStart(usageDate);
      });
      // this.select(usageDate)
    },
    submitForm(formName) {
      if (
        new Date(this.ruleForm.usageDate) <
        new Date().getTime() - 24 * 1000 * 3600
      ) {
        return this.$message("日期不能小于今日");
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let timeRange = this.ruleForm.timeRange;
          console.log("日期", this.ruleForm);
          let params = {
            ...this.ruleForm,
            usageStartTime: timeRange.length == 2 ? timeRange[0] : "",
            usageEndTime: timeRange.length == 2 ? timeRange[1] : "",
          };
          meeting(params).then((res) => {
            this.$message.success("预定成功！");
            this.dialog.visible = false;
            this.resetForm("ruleForm");
          });
          console.log("提交成功!!", this.ruleForm);
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    submodal(formName) {
      this.$refs[formName].resetFields();
      this.dialog.visible = false;
    },
    quertStart(date) {
      //选择日期，跳转到当前日期周
      let calendarApi = this.$refs.FullCalendar.getApi();
      //非空
      if (date != null) {
        this.select(date);
        calendarApi.gotoDate(date);
      } else {
        //跳转到今日
        calendarApi.today();
      }
    },
    /* 获取指定日期范围的所有日程信息 */
    toClick() {
      // 获取 FullCalendar 实例
      const calendar = this.$refs.FullCalendar.getApi();
      // 定义搜索范围的起始和结束时间
      const startDate = moment("2015-06-06");
      const endDate = moment("2028-06-08");
      // 获取日历中的所有事件
      const events = calendar.getEvents();
      // 根据范围条件筛选事件
      const filteredEvents = events.filter((event) => {
        // 获取事件的开始时间和结束时间
        const eventStart = moment(event.start);
        const eventEnd = moment(event.end);
        // 判断事件是否在范围内
        return (
          eventStart.isBetween(startDate, endDate, null, "[]") ||
          eventEnd.isBetween(startDate, endDate, null, "[]")
        );
      });

      // 处理筛选出的事件
      console.log(filteredEvents);
    },
    /* 点击会议弹窗具体内容*/
    handleEventClick(info) {
      let calendarApi = this.$refs.FullCalendar.getApi();
      calendarApi.refetchEvents();
    },
    handleClick(info) {
      console.log(info);
    },
    /* 关闭日程弹窗方法*/
    closeDialog() {
      this.showDialog = false;
    },
  },
  created () {
    this.getAllUser()
  }
};
</script>

<style scoped lang="scss">
.foot {
  text-align: center;
  margin-top: 20px;
}
.modal-title {
  text-align: center;
  font-size: 18px;
  font-weight: 500;
}
.title {
  .label {
    color: #606266;
    font-size: 14px;
    font-weight: 600;
    padding-right: 12px;
    margin-bottom: 20px;
    display: inline-block;
    width: 100px;
    text-align: right;
    // margin-left: 20px;
  }
}
::v-deep .title .el-col.el-col-6 {
  margin-bottom: 15px;
}
/* 修改抽屉样式 */
::v-deep .el-drawer__header {
  background-color: rgb(245, 245, 245);
  padding: 0px 20px;
  height: 50px;
  color: #000000;
  margin-bottom: 0px;
  //font-weight: bolder;
  font-size: 18px;
}

/* ::v-deep .el-drawer {
  background-color: #e3e3e3 !important
} */
.home {
  blockquote {
    padding: 10px 20px;
    margin: 0 0 20px;
    font-size: 17.5px;
    border-left: 5px solid #eee;
  }

  hr {
    margin-top: 20px;
    margin-bottom: 20px;
    border: 0;
    border-top: 1px solid #eee;
  }

  .col-item {
    margin-bottom: 20px;
  }

  ul {
    padding: 0;
    margin: 0;
  }

  font-family: "open sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-size: 13px;
  color: #676a6c;
  overflow-x: hidden;

  ul {
    list-style-type: none;
  }

  h4 {
    margin-top: 0px;
  }

  h2 {
    margin-top: 10px;
    font-size: 26px;
    font-weight: 100;
  }

  p {
    margin-top: 10px;

    b {
      font-weight: 700;
    }
  }

  .update-log {
    ol {
      display: block;
      list-style-type: decimal;
      margin-block-start: 1em;
      margin-block-end: 1em;
      margin-inline-start: 0;
      margin-inline-end: 0;
      padding-inline-start: 40px;
    }
  }
}
::v-deep .fc .fc-button-primary:disabled {
  background: transparent;
  color: #000000;
}
::v-deep .fc .fc-button-primary {
  background-color: transparent;
  color: #000000;
}

::v-deep.fc .fc-button:focus {
  box-shadow: transparent 0px 0px 0px 0px !important;
}
:deep(.el-form-item__content) {
  width: 200px;
}
:deep(.el-select.el-select--medium) {
  width: 200px;
}
::v-deep input.el-input__inner {
  padding-right: 0px !important;
}
.datechose {
  position: absolute;
  right: 183px;
  width: 107px;
  padding: 0px;
  :deep(input.el-input__inner) {
    padding-right: 0px !important;
  }
}
</style>
